package com.mvc.handlers;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

import com.smvc.entities.User;

@Controller
@RequestMapping("returnData")
@SessionAttributes(value={"name"})
public class ReturnDataController {
	
	private final String OK = "ok";
	
	/**
	 * 使用ModelAndView返回数据其实是把视图和数据一起返回了
	 * @return
	 */
	@RequestMapping("modelAndView")
	public ModelAndView modelAndView(){
		ModelAndView mv = new ModelAndView(OK);
		mv.addObject("modelAndView", "ModelAndViewInfo");
		return mv;
	}
	
	/**
	 * 使用Model返回数据
	 * @param model
	 * @return
	 */
	@RequestMapping("model")
	public String model(Model model){
		model.addAttribute("model", "ModelInfo");
		return OK;
	}
	
	/**
	 * 使用Map作为入参返回数据
	 * @param map
	 * @return
	 */
	@RequestMapping("map")
	public String map(Map<String, Object> map){
		map.put("map", "mapInfo");
		return OK;
	}
	
	/**
	 * 直接使用POJO对象返回数据，会在域里面放置的名字为类名首字母小写
	 * @param user
	 * @return
	 */
	@RequestMapping("pojo")
	public String pojo(User user){
		user.setId(2);
		user.setName("liuxing");
		return OK;
	}
	
	/**
	 * 使用@ModelAttribute修改POJO在域中的名字
	 * @param user
	 * @return
	 */
	@RequestMapping("modelAttribute")
	public String modelAttribute(@ModelAttribute("user2") User user){
		user.setId(2);
		user.setName("liuxing");
		return OK;
	}
	
	/**
	 * 需要放在Session中的对象，可以在类上面加上@SessionAttribute注解，指明放在Session中
	 * @param map
	 * @return
	 */
	@RequestMapping("sessionAttribute")
	public String sessionAttribute(Map<String,Object> map){
		map.put("name", "liuxing");
		return OK;
	}
	
	@RequestMapping("request")
	public String request(HttpServletRequest request){
		request.setAttribute("request", "requestInfo");
		return OK;
	}
}
